package net.godcode.t5c.components;

import org.apache.tapestry.ClientElement;
import org.apache.tapestry.ComponentResources;
import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.PageRenderSupport;
import org.apache.tapestry.TapestryConstants;
import org.apache.tapestry.annotations.BeginRender;
import org.apache.tapestry.annotations.Environmental;
import org.apache.tapestry.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry.annotations.IncludeStylesheet;
import org.apache.tapestry.annotations.Parameter;
import org.apache.tapestry.annotations.SetupRender;
import org.apache.tapestry.ioc.annotations.Inject;
import org.apache.tapestry.json.JSONObject;

@IncludeJavaScriptLibrary("slideshow.js")
@IncludeStylesheet("slideshow.css")
/**
 * A component for creating a slide show from a generic group of HTML
 * elements on the client side.
 * 
 * @author Chris Lewis Nov 8, 2007 <chris@thegodcode.net>
 * @version $Id: SlideShow.java 80 2007-12-28 20:36:08Z burningodzilla $
 */
public class SlideShow implements ClientElement {
	
	@Parameter(value = "2")
	private int interval;
	
	@Parameter(defaultPrefix = TapestryConstants.LITERAL_BINDING_PREFIX, value = "SlideShow.Tx.Crossfade")
	private String transition;
	
	@Parameter(value = "false")
	private boolean loop;
	
	@Parameter(value = "true")
	private boolean pauseOnHover;
	
	@Inject
	private ComponentResources resources;
	
	@Environmental
	private PageRenderSupport renderSupport;
	
	/** The client-side id. */
	private String clientId;
	
	/* Render phase. */
	
	@SetupRender
	void setupRender() {
		clientId = renderSupport.allocateClientId(resources.getId());
	}
	
	@BeginRender
	void beginRender(final MarkupWriter writer) {
		JSONObject jsConfig = new JSONObject();
		jsConfig.put("interval", interval);
		jsConfig.put("transition", transition);
		jsConfig.put("loop", loop);
		jsConfig.put("pauseOnHover", pauseOnHover);
		renderSupport.addScript("new SlideShow('%s', %s);", getClientId(), jsConfig);
	}
	
	/* End render phase. */
	
	public String getClientId() {
		return clientId;
	}
	
}